﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Logger;
using Common.BaseLibrary.Utils;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;

namespace DepartmentWork.Platform.Areas.DevelopArea.Controllers
{
    public class DocumentController : BaseController
    {
        //
        // GET: /DevelopArea/Doucment/

        public ActionResult ProjectDocumentList(Guid projectId)
        {
            #region 校验该登录用户是否是项目负责人

            ViewBag.IsDevelopLeader = false;

            #region 原版

            //if (CurrentUser.UserID.Length != 0)
            //{
            //    Guid userGuid = new Guid(CurrentUser.UserID);
            //    USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            //    PROJECT_DEVELOP_USER developUser = projectDevelopUserRepository.GetModel(r => r.USER_ID == user.USER_ID && r.PROJECT_ID == proId).FirstOrDefault();
            //    if (developUser != null)
            //    {
            //        if (developUser.USER_POSITION == 1)
            //        {
            //            ViewBag.IsDevelopLeader = true;
            //        }
            //    }
            //}

            #endregion


            #region 改版后

            //1 、 获取当前用户所在角色
            //2. 获取该角色 所具有的 所有 权限
            //3. 确认该角色是否具有该权限
            Guid userGuid = new Guid(CurrentUser.UserID);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            List<AUTHORITY_ROLE> authRoleList =
                authorityRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();



            for (int i = 0; i < authRoleList.Count; i++)
            {
                bool result = false;
                result =
                    empAuthorityRepository.GetModel(r => r.AUTHORITY_ID == authRoleList[i].AUTHORITY_ID)
                        .FirstOrDefault()
                        .AUTHORITY_TITLE.Contains("开发管理项目细节操作");
                if (result == true)
                {
                    ViewBag.IsDevelopLeader = true;
                    break;

                }
            }

            #endregion

            #endregion
            PROJECT_DEVELOP project = projectDevelopRepository.GetModel(r => r.PROJECT_DEVELOP_ID == projectId).FirstOrDefault();
            ViewBag.ProjectId = projectId;
            ViewBag.ProjectName = project.PROJECT_NAME;
            List<FILEINFO> fileList = fileRepository.GetModel(r => r.FILE_TYPE.Contains("DEVELOP_DOCUMENT")).ToList();
            List<ProjectDocumentViewModel> model=new List<ProjectDocumentViewModel>();

            List<PROJECT_DEVELOP_DOCUMENT> doucmentList =
                projectDevelopDocumentRepository.GetModel(r => r.PROJECT_ID == projectId).ToList();

            if (doucmentList.Count != 0)
            {
                Parallel.Invoke(() => model.AddRange(GetDoucmentFileInfos(fileList, doucmentList, "DEVELOP_DOCUMENT_REQUIRE")),
                    () => model.AddRange(GetDoucmentFileInfos(fileList, doucmentList, "DEVELOP_DOCUMENT_DESIGN")),
                    () => model.AddRange(GetDoucmentFileInfos(fileList, doucmentList, "DEVELOP_DOCUMENT_DATADICTIONARY")),
                    () => model.AddRange(GetDoucmentFileInfos(fileList, doucmentList, "DEVELOP_DOCUMENT_PUBLISH")));
            }

            return this.View(model);
        }

        private List<ProjectDocumentViewModel> GetDoucmentFileInfos(List<FILEINFO> fileList, List<PROJECT_DEVELOP_DOCUMENT> doucmentList, string type)
        {
            List<ProjectDocumentViewModel> list=new List<ProjectDocumentViewModel>();

            for (int i = 0; i < fileList.Count(); i++)
            {
                for (int j = 0; j < doucmentList.Count(); j++)
                {
                    if (fileList[i].CONTACT_ID == doucmentList[j].DOCUMENT_ID && fileList[i].FILE_TYPE == type)
                    {
                        ProjectDocumentViewModel item=new ProjectDocumentViewModel();
                        item.Creater = fileList[i].FILE_CREATER;
                        item.DocumentFileShowName = fileList[i].FILE_SHOWNAME;
                        item.DocumentFileSaveName = fileList[i].FILE_SAVENAME;
                        item.DocumentFilePath = fileList[i].FILE_SAVEPATH;
                        item.DocumentFileId = doucmentList[j].DOCUMENT_ID;
                        item.DocumentType = fileList[i].FILE_TYPE;
                        item.FileId = fileList[i].FILE_ID;
                        item.DocumentName = doucmentList[j].DOCUMENT_NAME;
                        list.Add(item);
                    }
                }
            }

            return list;
        }

        [HttpPost]
        public ActionResult CreateDocument(FormCollection collection)
        {
            PROJECT_DEVELOP_DOCUMENT document=new PROJECT_DEVELOP_DOCUMENT();
            FILEINFO file=new FILEINFO();
            document.DOCUMENT_NAME = collection["tb_DocumentName"];
            file.FILE_TYPE = collection["select_DocumentType"];
            document.PROJECT_ID = new Guid(collection["hid_ProjectId"]);
            document.CREATER = new Guid(CurrentUser.UserID);
            document.DOCUMENT_ID = Guid.NewGuid();
            //file.FILE_ID = Guid.NewGuid();
            file.CONTACT_ID = document.DOCUMENT_ID;
            file.FILE_CREATER = document.CREATER;

            string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Document\";
            int fileCount = this.Request.Files.Count;

            HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];
            this.Request.Files.CopyTo(upFiles, 0);
            if (upFiles[0].FileName != "")
            {
                try
                {
                    string fileSaveName = string.Empty;
                    HttpPostedFile hpf;
                    hpf = upFiles[0];
                    string fullUpLoadPath = "";
                    Guid fileName = Guid.NewGuid();
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));

                    file.FILE_ID = fileName;
                    file.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    file.FILE_SAVEPATH = fullUpLoadPath;
                    file.FILE_SAVENAME = fileSaveName;
                    file.FILE_CREATETIME = DateTime.Now;
                    //file.FILE_CREATER = new Guid(CurrentUser.UserID);
                    //file.FILE_TYPE = "DEVELOP_BUG";
                    //file.CONTACT_ID = bugModel.BUG_ID;

                    fileRepository.Insert(file);

                }
                catch (Exception ex)
                {
                    LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "文档提交失败！"+ex.Message);

                    return RedirectToAction("ProjectDocumentList", "Document", new { area = "DevelopArea", flag = "CreateFalse", flagInfo = ex.Message, projectId = document.PROJECT_ID });
                }
            }
            try
            {
                projectDevelopDocumentRepository.Insert(document);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "文档提交成功！" );

                return RedirectToAction("ProjectDocumentList", "Document", new { area = "DevelopArea", flag = "CreateTrue", projectId = document.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "文档提交失败！ 信息："+ex.Message);

                return RedirectToAction("ProjectDocumentList", "Document", new { area = "DevelopArea", flag = "CreateFalse", flagInfo = ex.Message, projectId = document.PROJECT_ID });
            }
        }


        public ActionResult DelDocument(Guid documentId)
        {
            PROJECT_DEVELOP_DOCUMENT document = new PROJECT_DEVELOP_DOCUMENT();
            try
            {
                document = projectDevelopDocumentRepository.GetModel(r => r.DOCUMENT_ID == documentId).FirstOrDefault();

                FILEINFO file = fileRepository.GetModel(r => r.CONTACT_ID == documentId && r.FILE_TYPE == "DEVELOP_DOCUMENT").FirstOrDefault();
                projectDevelopDocumentRepository.Delete(document);
                fileRepository.Delete(file);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "文档删除成功！");
                return RedirectToAction("ProjectDocumentList", "Document", new { area = "DevelopArea", flag = "DelTrue", projectId = document.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "文档删除失败！ 信息：" + ex.Message);
                return RedirectToAction("ProjectDocumentList", "Document", new { area = "DevelopArea", flag = "DelFalse", projectId = document.PROJECT_ID });
            }

        }

    }
}
